package lj.courseinterect.dao;

import lj.courseinterect.dao.i.ExamItemDao;
import lj.courseinterect.dao.i.StudentItemDao;
import lj.courseinterect.entity.ExamItem;
import lj.courseinterect.entity.StudentItem;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import java.util.List;

public class JpaStudentItemDao extends JpaDao<StudentItem, Long> implements StudentItemDao{

    public JpaStudentItemDao() {
        super(StudentItem.class);
    }


    
    @Override
    @Transactional(readOnly = true)

    public List<StudentItem> findByEiId(String eiId) {
        final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
        final CriteriaQuery<StudentItem> criteriaQuery = builder.createQuery(this.entityClass);

        Root<StudentItem> root = criteriaQuery.from(this.entityClass);
        Path<String> namePath = root.get("eiId");
        criteriaQuery.where(builder.equal(namePath, eiId));


        TypedQuery<StudentItem> typedQuery = this.getEntityManager().createQuery(criteriaQuery);
        List<StudentItem> studentItems = typedQuery.getResultList();

        if (studentItems.isEmpty()) {
            return null;
        }
        return studentItems;
    }

    @Override
    public List<StudentItem> findByStuId(String stuId) {
        final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
        final CriteriaQuery<StudentItem> criteriaQuery = builder.createQuery(this.entityClass);

        Root<StudentItem> root = criteriaQuery.from(this.entityClass);
        Path<String> namePath = root.get("stuId");
        criteriaQuery.where(builder.equal(namePath, stuId));


        TypedQuery<StudentItem> typedQuery = this.getEntityManager().createQuery(criteriaQuery);
        List<StudentItem> studentItems = typedQuery.getResultList();

        if (studentItems.isEmpty()) {
            return null;
        }
        return studentItems;
    }
}
